// pages/confirm_order/confirm_order.js
// 获取应用实例
const app = getApp()
var baseurl = app.baseurl.url;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    yuming: app.yuming.url,
    address: '',
    goods_id: '',
    list: '',
    img: '',
    number: 1,
    message: '',
    res_null: '',
    allprice: '',
    freight: '',// 运费
    w_total: '', // 运费总和
    allfreight: '' // 总运费
  },
  getDataBindTap: function (e) {
    var result = e.detail.value;
    this.setData({
      message: result
    })
    // console.log(this.data.message)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 详情列表
    this.setData({
      goods_id: options.goods_id
    })
    this.list(options.goods_id)
    this.address()
  },
  address() {
    wx.request({
      url: `${baseurl}/user.UserAddress/get_details`,
      method: 'POST',
      data: {
        status: 1,
        user_id: wx.getStorageSync("user_id"),
      },
      success: (res) => {
        // console.log(res.data.data);
        this.setData({
          address: res.data.data,
        })
        this.freight()
      }
    })
  },
  // 运费
  freight() {
    wx.request({
      url: `${baseurl}/order.Order/Freight`,
      method: 'POST',
      data: {
        user_id: wx.getStorageSync("user_id"),
        province: this.data.address.province,
      },
      success: (res) => {
        this.setData({
          res_null: res.data.data
        })
        let result = res
        // 判断不用运费的
        // if (res.data.data == 0) {
        if (res.data.data == null) {
          let price = 0 // 商品小计
          price = this.data.list.price * this.data.number
          wx.showToast({
            title: '地址暂不配送',
            icon: 'none',
            duration: 2000
          })
          this.setData({
            allfreight: '地址暂不配送',
            allprice: price
          })
        } else {
          // 运费
          let First_price = result.data.data.price  // 首件运费
          let lastprice = result.data.data.prices  // 多出的运费
          let sum = this.data.number  // 获取件数
          let price = 0 // 商品小计
          let allfreight = 0; // 总运费
          let freight = result.data.data  // 运费
          var weight = parseFloat(this.data.list.weight) * parseFloat(sum)  // 重量

          price = price + (this.data.list.price * this.data.number)
          // 运费改成按照每个省份的首件*1+（n-1）*多余价格
          // allfreight = First_price * 1 + (sum - 1) * lastprice
          // 运费 首重 + (n-1) * 多余价格
          allfreight = parseFloat(First_price) + parseFloat((weight - 1) * lastprice)
          allfreight = allfreight.toFixed(2)  // 按重量收费

          price = parseFloat(price) + parseFloat(allfreight)
          this.setData({
            allfreight: allfreight,
            allprice: price
          })
        }

      }
    })
  },
  // 详情
  list(id) {
    wx.request({
      url: `${baseurl}/good.Goods/good_details`,
      method: 'POST',
      data: {
        goods_id: id,
        user_id: wx.getStorageSync("user_id"),
      },
      success: (res) => {
        if (res.data.code == 400) {
          // console.log(res.data.data.data);
          this.setData({
            list: res.data.data.data,
            img: res.data.data.data.image[0]
            // collect: res.data.data.collect
          })
          // console.log(res.data.data.data.image[0]);
          // console.log(this.data.list.price);
          let a = this.data.list.price * this.data.number
          let f = this.data.list.weight * this.data.w_total
          let allprice = parseFloat(a) + parseFloat(f)
          this.setData({
            allprice: allprice,
            allfreight: f

          })
          // console.log(allprice);
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }


      }
    })
  },
  add() {
    let num = this.data.number
    if (num < 999) {
      num++
      this.setData({
        number: num
      });
      this.freight()
    } else {
      wx.showToast({
        title: '库存不足',
        icon: 'none',
        duration: 2000
      })
    }
  },
  reduce() {
    let num = this.data.number
    if (num > 1) {
      num--
      this.freight()
      this.setData({
        number: num
      });

    } else {
      wx.showToast({
        title: '至少数量为1件',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 立即支付
  puy() {
    console.log(this.data.address);
    if (this.data.address == null) {
      wx.showToast({
        title: '请添加收货地址 ！',
        icon: 'none',
        duration: 2000
      })
    } else {

      if (this.data.res_null == null) {
        wx.showToast({
          title: '地址不支持配送 ！',
          icon: 'none'
        })
      } else {
        wx.request({
          url: `${baseurl}/order.Order/order_add`,
          data: {
            number: this.data.number,
            total_price: this.data.allprice,
            user_id: wx.getStorageSync("user_id"),
            openid: wx.getStorageSync("openid"),
            phone: this.data.address.phone,
            user_name: this.data.address.user_name,
            province: this.data.address.province,
            city: this.data.address.city,
            area: this.data.address.area,
            address: this.data.address.address,
            goods_id: this.data.goods_id,
            message: this.data.message
          },
          success: (res) => {
            console.log(res.data);
            // var appid = getApp().globalData.appid; //appid
            // console.log(appid);
            let timeStamp = res.data.data.data_pay_sign.timeStamp
            let nonceStr = res.data.data.data_pay_sign.nonceStr
            let pack = res.data.data.data_pay_sign.package
            let paySign = res.data.data.data_pay_sign.paySign
            let signType = res.data.data.data_pay_sign.signType
            wx.requestPayment({
              "timeStamp": timeStamp,
              "nonceStr": nonceStr,
              "package": pack,
              "signType": signType,
              "paySign": paySign,
              "success": function (res) {
                // console.log('111', res);
                wx.showToast({
                  title: '支付成功',
                  // icon: 'none',
                  duration: 2000
                })
                // 支付成功
                wx.reLaunch({
                  url: '/pages/success/success',
                })
              },
              "fail": function (res) {
                // console.log('222', res);
                wx.showToast({
                  title: '支付失败',
                  icon: 'none',
                  duration: 2000
                })
                wx.reLaunch({
                  url: '/pages/order/order'
                })
                // setTimeout(() => {
                //   wx.reLaunch({
                //     url: '/pages/order/order'
                //   })
                // }, 500);

              },
              "complete": function (res) {
                // 接口调用结束的回调函数（调用成功、失败都会执行）
              }
            })
          }
        })
      }

    }


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.address()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})